package com.xl.xlservice.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.xl.xlservice.exception.GlobalException;
import com.xl.xlservice.model.Order;
import com.xl.xlservice.model.ResultData;
import com.xl.xlservice.model.User;
import com.xl.xlservice.service.UserService;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("api/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/queryUser")
    // 对应的 `handleException` 函数需要位于 `GlobalException` 类中，并且必须为 static 函数.
    @SentinelResource(value = "queryUser", blockHandler = "handleException", blockHandlerClass = {GlobalException.class})
    public ResultData<List<User>> queryUser(@RequestBody User user){
        ResultData<List<User>> resultData = new ResultData<>();
        // try {
        //     // 设置一个资源名称为 queryUser
        //     Entry ignored = SphU.entry("queryUser");
            return resultData.buildResultData(0,"成功",userService.queryUser(user),0);
        // } catch (BlockException e) {
        //     return resultData.buildResultData(-1,"系统繁忙",null,0);
        // }
    }

    @RequestMapping("/addUser")
    public void addUser(@RequestBody User user){
        try {
            userService.addUser(user);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @RequestMapping("/queryOrder")
    public List<Order> queryUser(@RequestBody Order order){
        return userService.queryOrder(order);
    }


    /**
     * 使用代码编写流控规则，项目中不推荐使用，这是硬编码方式
     *
     * 注解 @PostConstruct 的含义是：本类构造方法执行结束后执行
     */
    // @PostConstruct
    // private static void initFlowRule(){
    //     //流控规则集合
    //     List<FlowRule> rules = new ArrayList<>();
    //     //创建规则
    //     FlowRule rule = new FlowRule();
    //     //设置受保护的资源，sentinel会对哪个资源生效
    //     rule.setResource("queryUser");
    //     //设置流控规则 QPS 限流阈值类型：QPS、并发线程数
    //     rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
    //     // 设置受保护的资源的阈值
    //     rule.setCount(2);
    //     //设置流控手段：快速失败
    //     rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
    //     rules.add(rule);
    //     //加载配置好的规则
    //     FlowRuleManager.loadRules(rules);
    // }

}
